package com.jay.tools.web.event;

import android.webkit.JavascriptInterface;

import com.alibaba.fastjson.JSON;
import com.jay.tools.utils.LogUtil;
import com.jay.tools.web.WebFragment;

/**
 * Created by tan on 2017/9/22 022.
 * 用于和原生应用进行交互
 */

public final class LatteWebInterface {

    private final WebFragment WEB_FRAGMENT;

    private LatteWebInterface(WebFragment webFragment) {
        this.WEB_FRAGMENT = webFragment;
    }

    public static LatteWebInterface create(WebFragment fragment) {
        return new LatteWebInterface(fragment);
    }

    // 接收JS中的返回值
    @JavascriptInterface  //必须加入此注解event才会响应，否则会认为是不安全和不可应用的
    public String event(String params) {
        LogUtil.d("LatteWebInterface", "响应事件：" + params);
        // 这里是通过外部的action事件来绑定自己的事件
        final String action = JSON.parseObject(params).getString("action");
        Event event = EventManager.getInstance().getEvent("test");
        if (null != event) {
            event.setAction(action);
            event.setFragment(WEB_FRAGMENT);
            event.setContext(WEB_FRAGMENT.getContext());
            event.setUrl(WEB_FRAGMENT.getUrl());
            return event.execute(params);
        }
        return null;
    }
}
